//
//  XMImgSelect.m
//  XMJJ_zmy
//
//  Created by 丁浩 on 2025/7/10.
//

#import "XMImgSelect.h"
#import <AssetsLibrary/AssetsLibrary.h>
#import <Photos/Photos.h>
#import <PhotosUI/PhotosUI.h>
#import <MobileCoreServices/MobileCoreServices.h>

@interface XMImgSelect () <PHPickerViewControllerDelegate, UIImagePickerControllerDelegate, UINavigationControllerDelegate>

@end

@implementation XMImgSelect

+ (instancetype)sharedInstance {
    static XMImgSelect *sharedInstance = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        sharedInstance = [[self alloc] init];
    });
    return sharedInstance;
}


- (void)selectImgFromLibraryOnVC:(XMBaseViewController *)presentVC {
    dispatch_async(dispatch_get_main_queue(), ^{
        if (@available(iOS 14.0, *)) {
            PHPickerConfiguration *configuration = [[PHPickerConfiguration alloc] init];
            configuration.filter = [PHPickerFilter anyFilterMatchingSubfilters:@[ [PHPickerFilter imagesFilter]]];
            configuration.selectionLimit = 9;
            PHPickerViewController *picker = [[PHPickerViewController alloc] initWithConfiguration:configuration];
            picker.delegate = self;
            picker.modalPresentationStyle = UIModalPresentationFullScreen;
            picker.view.backgroundColor = [UIColor whiteColor];
            [presentVC presentViewController:picker animated:YES completion:nil];
        }
        else {
            if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]) {
                UIImagePickerController *picker = [[UIImagePickerController alloc] init];
                picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
                picker.mediaTypes = [UIImagePickerController availableMediaTypesForSourceType:UIImagePickerControllerSourceTypePhotoLibrary];
                picker.mediaTypes = @[@"public.image"];
                picker.delegate = self;
                [presentVC presentViewController:picker animated:YES completion:nil];
            }
        }
    });
}

- (void)selectImgFromCameraOnVC:(XMBaseViewController *)presentVC {
    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
        UIImagePickerController *picker = [[UIImagePickerController alloc] init];
        picker.sourceType = UIImagePickerControllerSourceTypeCamera;
        picker.mediaTypes = @[@"public.image"];
        picker.delegate = self;
        [presentVC presentViewController:picker animated:YES completion:nil];
    }
    else {
        [MBProgressHUD showError:@"无手机权限"];
    }
}

#pragma mark - Delegate
- (void)picker:(PHPickerViewController *)picker didFinishPicking:(NSArray<PHPickerResult *> *)results API_AVAILABLE(ios(14)) {
    dispatch_async(dispatch_get_main_queue(), ^{
      [picker dismissViewControllerAnimated:YES completion:nil];
      [[[UIApplication sharedApplication] keyWindow] endEditing:YES];
    });

    if (!results || results.count == 0) {
        return;
    }

    __block int totalCount = 0;
    XMWeakSelf;
    NSMutableArray *imgArr = [NSMutableArray array];
    for (PHPickerResult *result in results) {
        NSItemProvider *itemProvoider = result.itemProvider;
        if ([itemProvoider hasItemConformingToTypeIdentifier:(NSString *)kUTTypeImage]) {
            [itemProvoider loadDataRepresentationForTypeIdentifier:(NSString *)kUTTypeImage completionHandler:^(NSData * _Nullable data, NSError * _Nullable error) {
                dispatch_async_and_wait(dispatch_get_main_queue(), ^{
                    UIImage *img = [UIImage imageWithData:data];
                    if (img) {
                        [imgArr addObject:img];
                    }
                    totalCount += 1;
                    if (totalCount == results.count) {
                        [weakSelf imgSelectSuccess:imgArr];
                    }
                });
            }];
        }
        else {
            totalCount += 1;
            if (totalCount == results.count) {
                [weakSelf imgSelectSuccess:imgArr];
            }
        }
    }
}

- (void)imgSelectSuccess:(NSArray *)imgArr {
    if (imgArr.count > 0) {
        self.imgSelectBlock ? self.imgSelectBlock(imgArr) : nil;
    }
    else {
        [MBProgressHUD showError:@"图片选择错误"];
    }
}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<UIImagePickerControllerInfoKey,id> *)info {
    XMWeakSelf;
    [picker dismissViewControllerAnimated:YES completion:^{
        UIImage *selectImg = [info objectForKey:UIImagePickerControllerOriginalImage];
        weakSelf.imgSelectBlock ? weakSelf.imgSelectBlock(@[selectImg]) : nil;;
    }];
}

@end
